import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as loginApi, getUserInfo as getUserInfoApi, logout as logoutApi } from '@/api/auth'
import type { LoginForm, LoginResponse } from '@/types'

export const useUserStore = defineStore('user', () => {
  // 用户token
  const token = ref('')
  
  // 用户信息
  const userInfo = ref<any>(null)
  
  // 用户权限
  const permissions = ref<string[]>([])

  // 登录（模拟登录，不调用后端API）
  const login = async (loginForm: LoginForm): Promise<void> => {
    try {
      // 模拟登录成功，不调用实际API
      const mockResponse: LoginResponse = {
        token: 'mock-token-' + Date.now(),
        userInfo: {
          id: 1,
          name: '管理员',
          username: loginForm.username,
          role: 'admin',
          permissions: ['*'],
          avatar: '',
          phone: '13800138000',
          email: 'admin@example.com',
          createdAt: '2024-01-01 00:00:00'
        }
      }
      token.value = mockResponse.token
      userInfo.value = mockResponse.userInfo
      permissions.value = mockResponse.userInfo.permissions || []
    } catch (error) {
      throw error
    }
  }

  // 获取用户信息（模拟获取，不调用后端API）
  const getUserInfo = async (): Promise<void> => {
    try {
      // 模拟用户信息
      const mockResponse = {
        id: 1,
        name: '管理员',
        username: 'admin',
        role: 'admin',
        permissions: ['*'],
        avatar: '',
        phone: '13800138000',
        email: 'admin@example.com',
        createdAt: '2024-01-01 00:00:00'
      }
      userInfo.value = mockResponse
      permissions.value = mockResponse.permissions || []
    } catch (error) {
      throw error
    }
  }

  // 登出
  const logout = async (): Promise<void> => {
    try {
      await logoutApi()
    } catch (error) {
      console.error('Logout error:', error)
    } finally {
      token.value = ''
      userInfo.value = null
      permissions.value = []
    }
  }

  // 检查权限
  const hasPermission = (permission: string): boolean => {
    return permissions.value.includes(permission) || permissions.value.includes('*')
  }

  // 检查角色
  const hasRole = (role: string): boolean => {
    return userInfo.value?.role === role || userInfo.value?.role === 'admin'
  }

  // 获取用户列表
  const fetchUserList = async (params: any = {}) => {
    try {
      // 这里应该调用实际的API
      // const response = await getUserListApi(params)
      // 模拟返回数据
      const mockData = {
        list: [
          {
            id: 1,
            name: '张三',
            phone: '13800138001',
            level: 'normal',
            balance: '156.50',
            disposalCount: 25,
            totalEarnings: '320.80',
            createdAt: '2024-01-10 10:30:00',
            lastLoginAt: '2024-01-15 14:20:00',
            status: 'active'
          },
          {
            id: 2,
            name: '李四',
            phone: '13800138002',
            level: 'vip',
            balance: '289.30',
            disposalCount: 42,
            totalEarnings: '580.60',
            createdAt: '2024-01-08 16:45:00',
            lastLoginAt: '2024-01-15 09:15:00',
            status: 'active'
          }
        ],
        total: 100
      }
      return mockData
    } catch (error) {
      throw error
    }
  }

  return {
    token,
    userInfo,
    permissions,
    isLoggedIn: computed(() => !!token.value),
    login,
    getUserInfo,
    logout,
    hasPermission,
    hasRole,
    fetchUserList
  }
}, {
  persist: {
    key: 'user-store',
    storage: localStorage,
    paths: ['token', 'userInfo', 'permissions']
  }
})